package com.deli.springboot.demoquartz;

import org.junit.experimental.theories.Theories;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;

import java.util.Date;

public class HelloScheduler {
    public static void main(String[] args) throws SchedulerException, InterruptedException {
        //创建一个jobDetail实例，将该实例绑定HelloJob.class
        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
                .withIdentity("myJob", "group1")
                //设置参数
                /*.usingJobData("message", "hello world")
                .usingJobData("math", 2.22F)*/
                .build();
        //获取到
        System.out.println(jobDetail.getKey().getGroup());
        System.out.println(jobDetail.getKey().getName());
        Date startDate = new Date();
        startDate.setTime(startDate.getTime()+3000L);
        Date endDate = new Date();
        endDate.setTime(endDate.getTime()+6000L);
        Trigger trigger = TriggerBuilder
                .newTrigger()
                //定义Trigger的名字，和组名，名字要，group是有默认值为DEFAULT
                .withIdentity("myTrigger", "group1")
                //设置参数
                //.usingJobData("message", "hello java")
                //.usingJobData("triggerInt", 2222)
                //设置启动时间
                //.startAt(startDate)
                //.endAt(endDate)
                //创建一个Trigger实例,定义该job立即执行，每隔两秒重复执行一次，一直执行下去
                .withSchedule(
                        //设置执行时间和次数
                        //有两种设置方式，1：cron表达式，2：传统的设置一些常量，次数。个人喜欢cron表达式，因为代码简短
                        CronScheduleBuilder.cronSchedule("0/2 * * * * ? *")
                        //SimpleScheduleBuilder.simpleSchedule().withRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY)
                        /*SimpleScheduleBuilder
                                .simpleSchedule()
                                .withIntervalInSeconds(2)
                                .repeatForever()*/)
                .build();
        //创建Scheduler实例
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail,trigger);
        Thread.sleep(2000L);
        //挂载（相当于暂停）,当scheduler挂载之后是可以再次启动的
        scheduler.standby();
        //关闭，当任务调度关闭之后，是不可以再次唤醒scheduler
        scheduler.shutdown();
        //直接关闭，不等待任务全部完成
        //scheduler.shutdown(false);
        //等待全部的任务完成之后，再去关闭
        //scheduler.shutdown(true);
    }
}
